package com.bkhech.service;


import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import com.bkhech.enums.FriendRequestVerifyStatus;
import com.bkhech.enums.YesOrNo;
import com.bkhech.mapper.FriendRequestMapper;
import com.bkhech.mapper.FriendshipMapper;
import com.bkhech.pojo.FriendRequest;
import com.bkhech.pojo.Friendship;
import com.bkhech.pojo.bo.NewFriendRequestBO;
import com.bkhech.pojo.vo.NewFriendsVO;
import com.bkhech.utils.PagedGridResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * FriendRequestService
 *
 * @author guowm
 * @date 2024-11-06
 */
@Service
@Slf4j
public class FriendRequestService {
    @Resource
    private FriendRequestMapper friendRequestMapper;

    @Resource
    private FriendshipMapper friendshipMapper;

    @Resource
    private PlatformTransactionManager platformTransactionManager;

    @Resource
    private TransactionDefinition transactionDefinition;

    /**
     * 添加好友请求
     *
     * @param newFriendRequestBO
     */
    @Transactional
    public void addNewRequest(NewFriendRequestBO newFriendRequestBO) {
        // 先删除以前的记录
        this.deleteHistoryByMyIdAndFriend(newFriendRequestBO);
        // 再新增记录
        FriendRequest addFriendRequest = new FriendRequest();
        BeanUtils.copyProperties(newFriendRequestBO, addFriendRequest);
        addFriendRequest.setVerifyStatus(FriendRequestVerifyStatus.WAIT.type);
        addFriendRequest.setRequestTime(LocalDateTimeUtil.now());
        friendRequestMapper.insert(addFriendRequest);
    }

    private void deleteHistoryByMyIdAndFriend(NewFriendRequestBO newFriendRequestBO){
        QueryWrapper<FriendRequest> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FriendRequest::getMyId, newFriendRequestBO.getMyId())
                .eq(FriendRequest::getFriendId, newFriendRequestBO.getFriendId());
        friendRequestMapper.delete(queryWrapper);
    }

    /**
     * 根据用户的id分页查询好友申请列表
     *
     * @param userId   用户id
     * @param page     当前页码
     * @param pageSize 每页展示的数量
     * @return
     */
    public PagedGridResult<NewFriendsVO> queryNewFriendList(String userId, Integer page, Integer pageSize) {

        Page<NewFriendsVO> pageReq = new Page(page, pageSize);
        Page<NewFriendsVO> newFriendsVOPage = friendRequestMapper.queryNewFriendList(pageReq, userId);

        return PagedGridResult.getPageInfo(page, pageSize, newFriendsVOPage.getTotal(), newFriendsVOPage.getRecords());
    }


    //    @Transactional(rollbackFor = Exception.class)
    public void passNewFriend(String friendRequestId, String friendRemark) {
        FriendRequest friendRequest = this.getSingle(friendRequestId);
        // 通过方得用户id
        String myselfId = friendRequest.getFriendId();
        // 被通过放得用户id
        String myFriendId = friendRequest.getMyId();
        // 创建双方友好关系
        Friendship friendshipSelf = new Friendship();
        LocalDateTime nowTime = LocalDateTimeUtil.now();
        friendshipSelf.setMyId(myselfId);
        friendshipSelf.setFriendId(myFriendId);
        friendshipSelf.setFriendRemark(friendRemark);
        friendshipSelf.setIsBlack(YesOrNo.NO.type);
        friendshipSelf.setIsMsgIgnore(YesOrNo.NO.type);
        friendshipSelf.setCreatedTime(nowTime);
        friendshipSelf.setUpdatedTime(nowTime);

        Friendship friendshipOpposite = new Friendship();
        friendshipOpposite.setMyId(myFriendId);
        friendshipOpposite.setFriendId(myselfId);
        friendshipOpposite.setFriendRemark(friendRequest.getFriendRemark());
        friendshipOpposite.setIsBlack(YesOrNo.NO.type);
        friendshipOpposite.setIsMsgIgnore(YesOrNo.NO.type);
        friendshipOpposite.setCreatedTime(nowTime);
        friendshipOpposite.setUpdatedTime(nowTime);
        TransactionStatus transaction = null;

        try {
            transaction = platformTransactionManager.getTransaction(transactionDefinition);
            friendshipMapper.insert(friendshipSelf);
//            platformTransactionManager.commit(transaction);

            friendshipMapper.insert(friendshipOpposite);
//            platformTransactionManager.commit(transaction);
            // 把状态修改为已通过。A 通过 B 的请求之后，需要把双方的好友请求记录都设置为 “通过”
            friendRequest.setVerifyStatus(FriendRequestVerifyStatus.SUCCESS.type);
            friendRequestMapper.updateById(friendRequest);
//            platformTransactionManager.commit(transaction);

            // 还有一种情况， A 添加 B ，B 没有通过，所以 A 发出的好友请求过期了；
            // 但是过期后，B 向 A 发起好友请求， 所以 B 被 A 通过之后，那么两边的请求都应该“通过”，此时需要把状态设置为通过即可
            QueryWrapper<FriendRequest> updateWrapper = new QueryWrapper<>();
            updateWrapper.lambda().eq(FriendRequest::getMyId, myFriendId)
                    .eq(FriendRequest::getFriendId, myselfId);
            FriendRequest friendRequestOpposite = new FriendRequest();
            friendRequestOpposite.setVerifyStatus(FriendRequestVerifyStatus.SUCCESS.type);
            friendRequestMapper.update(friendRequestOpposite, updateWrapper);

            platformTransactionManager.commit(transaction);
        } catch (Exception e) {
            log.info("添加好友失败，FriendRequestService.passNewFriend()方法报错：{}， {}", e, e.getMessage());
            // 如果失败就回滚
            platformTransactionManager.rollback(transaction);
            throw new RuntimeException(e);
        }

    }


    public FriendRequest getSingle(String friendRequestId) {
        return friendRequestMapper.selectById(friendRequestId);
    }
}
